<template>
	<view class="layout pageBg">
	<post-nav-bar title="创意菜谱"></post-nav-bar>
	<view class="blank"></view>
	</view>
    <view class="container">
      <u-form :model="formData" :rules="rules" ref="formRef">
        <!-- 食材输入 -->
        <u-form-item label="主要食材" prop="foodMaterial">
          <u-input 
            v-model="formData.foodMaterial" 
            placeholder="请输入食材，多个用逗号分隔（如：白菜，猪肉）"
            @blur="formRef.validateField('foodMaterial')"
          />
        </u-form-item>
  
        <!-- 烹饪方式选择 -->
        <u-form-item label="烹饪方式" prop="cookingMethod">
          <u-input
            v-model="formData.cookingMethod"
            placeholder="请选择烹饪方式"
            disabled
            @click="showPicker"
            suffix-icon="arrow-down"
          />
        </u-form-item>
  
        <!-- 提交按钮 -->
        <u-button 
		  color="#f56c6c"
          type="primary" 
          @click="handleSubmit"
          :loading="loading"
          :disabled="loading"
        >{{ loading ? '提交中...' : '提交' }}</u-button>
      </u-form>
  
      <!-- 显示响应结果 -->
      <view class="response-area" v-if="responseData.length > 0">
		
        <view v-for="(item, index) in responseData" :key="index">
          <!-- 菜谱步骤 -->
          <view v-if="item.point" class="response-item">
            <text class="point">{{ item.point }}.</text>
            <text class="content">{{ item.content }}</text>
          </view>
  
          <!-- 图片展示 -->
          <view v-if="item.img_url" class="image-container">
            <u-image
              :src="item.img_url"
              width="100%"
              height="300rpx"
              mode="aspectFit"
              :lazy-load="true"
			
            >
			<template v-slot:error>
			<view class="error-text">图片加载失败</view>
			</template>
			</u-image>
          </view>
        </view>
      </view>
  
      <!-- 烹饪方式选择器 -->
      <u-picker
        :show="showCookingPicker"
        :columns="[cookingOptions]"
        keyName="label"
		confirmColor="#FF4D4F"
        @confirm="handlePickerConfirm"
        @cancel="showCookingPicker = false"
		:closeOnClickOverlay="true"
		@close="showCookingPicker = false"
      ></u-picker>
    </view>
  </template>
  
  <script setup>
  import { reactive, ref } from 'vue'
  
  const formRef = ref(null)
  const loading = ref(false)
  const showCookingPicker = ref(false)
  
  // 表单数据
  const formData = reactive({
    foodMaterial: '',
    cookingMethod: ''
  })
  
  // 响应数据
  const responseData = ref([])
  
  // 烹饪方式选项
  const cookingOptions = [
    { label: '煎', value: '煎' },
    { label: '炒', value: '炒' },
    { label: '煮', value: '煮' },
    { label: '蒸', value: '蒸' },
    { label: '烤', value: '烤' }
  ]
  
  // 验证规则
  const rules = {
    foodMaterial: [
      { 
        required: true, 
        message: '请输入食材',
        trigger: ['blur', 'change']
      },
      {
        pattern: /^[\u4e00-\u9fa5，]+$/,
        message: '只能输入中文和逗号',
        trigger: ['blur', 'change']
      }
    ],
    cookingMethod: [
      {
        required: true,
        message: '请选择烹饪方式',
        trigger: ['change']
      }
    ]
  }
  
  // 显示选择器
  const showPicker = () => {
    showCookingPicker.value = true
  }
  
  // 选择器确认
  const handlePickerConfirm = (e) => {
    const selected = e.value[0]
    formData.cookingMethod = selected.value
    formRef.value.validateField('cookingMethod')
    showCookingPicker.value = false
  }
  
  // 提交处理
  const handleSubmit = async () => {
    try {
      // 执行完整验证
      await formRef.value.validate()
      loading.value = true
      
      // 发送请求
      const res = await uni.request({
        url: 'http://120.26.113.115:5000/get_create_recipe',
        method: 'POST',
        data: {
          ingredients: formData.foodMaterial,
          cooking_method: formData.cookingMethod
        },
        header: {
          'Content-Type': 'application/json'
        } 
      })
	  console.log(res)
	  if (!res || res.statusCode !== 200) {
	    console.error('请求失败:', requestError || res.data?.message || '未知错误');
	    throw new Error(res.data?.message || '请求失败，请稍后重试');
	  }
	  
	  console.log('原始响应数据:', JSON.stringify(res.data, null, 2));
	  
	  // 确保 res.data 是一个数组
	  if (Array.isArray(res.data)) {
	    responseData.value = res.data.map(item => {
	      // 打印每个数据项
	      console.log('处理数据项:', JSON.stringify(item));
	      
	      // 格式化内容换行
	      if (item.content) {
	        return {
	          ...item,
	          content: item.content.replace(/\n/g, '\n') // 这里实际上不需要替换，因为'\n'已经是换行符
	        };
	      }
	      return item;
	    });
	    
	    console.log('处理后的响应数据:', JSON.stringify(responseData.value, null, 2));
	  } else {
	    console.warn('预期的响应数据应为数组，但实际得到了:', typeof res.data);
	    // 根据实际情况处理非数组的响应数据
	  }

      uni.showToast({ title: '提交成功', icon: 'success' })
      
    } catch (error) {
      if (error.error) {
        uni.showToast({ 
          title: error.error.message || '提交失败',
          icon: 'none'
        })
      } else {
        uni.showToast({ 
          title: error.message || '提交失败', 
          icon: 'none'
        })
      }
    } finally {
      loading.value = false
    }
	
	const handleImageError = (event) => {
	      console.error('Image failed to load', event);
	      // 你可以在这里添加更多的错误处理逻辑，比如替换为默认图片
	      item.value.img_url = 'https://example.com/default-image.jpg';
	    };
  }
  </script>
  
  <style scoped>
  /* 保持原有样式不变 */
  .container {
    padding: 20px;
  }
  
  .blank {
  	height: 60rpx;
  	background-color: ghostwhite;
  	position: fixed;
  	top: 70rpx;
  	left: 0;
  	width: 100%;
  	z-index: 8;
  }
  
  .response-area {
    margin-top: 30px;
    padding: 15px;
    background-color: #f8f8f8;
    border-radius: 8px;
  }
  
  .response-item {
    margin-bottom: 20px;
  }
  
  .point {
    font-weight: bold;
    color: #f56c6c;
    margin-right: 8px;
  }
  
  .content {
    color: #333;
    line-height: 1.6;
    white-space: pre-wrap;
  }
  
  .image-container {
    margin-top: 20px;
    border-radius: 8px;
    overflow: hidden;
    background-color: #fff;
    padding: 10px;
  }
  
  /* 烹饪方式输入框样式 */
  :deep(.u-input__input[disabled]) {
    color: #333 !important;
    background-color: #fff !important;
  }
  
  .error-text {
    color: #ff4444;
    font-size: 14px;
    text-align: center;
    padding: 20px;
  }
  </style>